package com.waypolice.manager.controller;

import com.waypolice.base.BaseController;
import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.FastDfsClient;
import com.waypolice.common.utils.MathUtils;
import com.waypolice.manager.service.*;
import com.waypolice.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @author zyp
 * @description 档案借阅控制器
 * @create 2019-02-27 16:19
 */
@Controller
@Api(value = "档案借阅控制器", description = "档案的借阅")
@RequestMapping(value="/pcwindow")
public class BorrowArchiveAction extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BorrowArchiveAction.class);

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @Autowired
    private ActDefineService actDefineService;

    @Autowired
    private BorRegisterService borRegisterService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private VolAndItemService volAndItemService;

    @Autowired
    private BorAuditService borAuditService;

    @Autowired
    protected UserService userService;

    @Autowired
    protected CmsSinItemService cmsSinItemService;

    /**
     * @author:zyp
     * @description 借阅管理跳转
     * @date: 2019/2/27 16:21
     * @return
     */
    @ApiOperation(value = "借阅管理跳转")
    @RequiresPermissions("cms:borrowArchive:read")
    @RequestMapping(value = "/toBorrowArchive")
    public String jumpToBorrowPage(HttpServletRequest req){
        String id = req.getParameter("id");
        //当前搜索的文件类型：卷或者件
        String type =req.getParameter("type");
        if(StringUtils.isNotBlank(id)&&StringUtils.isNotBlank(type)){
            String carrierType = volAndItemService.getCarrierType(type,id);
            req.setAttribute("carrierType",carrierType);
        }
        req.setAttribute("type",type);
        req.setAttribute("id",id);
        return "/borrowManager/borrowArchive";
    }

    /**
     * @author:zyp
     * @description 发送借阅申请
     * @date: 2019/3/18 13:42
     * @return
     */
    @ApiOperation("发送借阅申请")
    @RequiresPermissions("cms:borrowArchive:borrow")
    @RequestMapping(value = "/sendBorAct")
    @ResponseBody
    public Object sendBorAct(MultipartFile file, HttpServletRequest request) throws Exception {
        CmsBorRegister cmsBorRegister=new CmsBorRegister();

        /* 获取前台数据信息*/
        //借阅的文件形式  卷、件
        String fileType = request.getParameter("fileType");
        //有可能是多件借阅
        String borrowId = request.getParameter("borrowId");
        String borDept = request.getParameter("borDept");
        String borType = request.getParameter("borType");
//        Date borTime = DateTimeUtil.strToDate(request.getParameter("borTime"));
        Date planReturnTime = DateTimeUtil.strToDate(request.getParameter("planReturnTime"));
        String borPurPose = request.getParameter("borPurPose");

        //当动态制定时应用
        String userName = request.getParameter("userName");
        String delegateUser = request.getParameter("delegateUser");

        String hallType = request.getParameter("hallType");

        long fileTypeLong = Long.parseLong(fileType);
        String[] borrowIds = borrowId.split(",");

        //获取当前登录人的账号
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        cmsBorRegister.setBorUserId((long)user.getUserId());
        cmsBorRegister.setBorType(Long.parseLong(borType));
        cmsBorRegister.setBorPurpose(borPurPose);
//        cmsBorRegister.setBorTime(borTime);
        cmsBorRegister.setPlanReturnTime(planReturnTime);
        cmsBorRegister.setCreateTime(new Date());

        if(file!=null){
            // 取扩展名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            // 上传到图片服务器
            FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
            String fastDfSUrl = fastDFSClient.uploadFile(file.getBytes(),extName);
            String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
            cmsBorRegister.setBorDeptDescription(borDept);
            cmsBorRegister.setBorAttestUrl(imagesUrl);
        }else{
            cmsBorRegister.setBorDeptId(Long.parseLong(borDept));
        }

        CmsJudVolume cmsJudVolume = null;
        CmsJudItem cmsJudItem = null;
        CmsSinItem cmsSinItem = null;
        if(BorrowConstant.BORROW_FILE_VOLUM==fileTypeLong){
            //默认只选一个借阅id
            cmsJudVolume = volAndItemService.selectCmsJudVolumeByVolId(MathUtils.string2long(borrowIds[0]));
            //档案类型：文书、审计
            cmsBorRegister.setFileType(cmsJudVolume.getVolClass());
        }else if (BorrowConstant.BORROW_FILE_ITEM == fileTypeLong){
            //只需选择一个借阅件即可了解当前借阅卷
            cmsJudItem = volAndItemService.selectByItemId(MathUtils.string2long(borrowIds[0]));
            Long itmeVolId = cmsJudItem.getItmeVolId();
            cmsJudVolume = volAndItemService.selectCmsJudVolumeByVolId(itmeVolId);
            //档案类型：文书、审计
            cmsBorRegister.setFileType(cmsJudVolume.getVolClass());
        }else if(BorrowConstant.BORROW_FILE_SIN_ITEM==fileTypeLong){
            //如果是单件
            cmsSinItem = cmsSinItemService.selectSinItemById(MathUtils.string2long(borrowIds[0]));
            cmsBorRegister.setFileType(cmsSinItem.getItemExp1());
        }
        //获取当前借阅的最新的流程
        UpmsActDefine upmsActDefine = actDefineService.getNewAct("borAct");
        if(upmsActDefine==null){
            return new CmsResult(0,"借阅失败，请找系统管理员确认流程是否定义",0);
        }

        //获取流程的唯一标识
        String key = upmsActDefine.getAdKey();
        cmsBorRegister.setCreateTime(new Date());
        cmsBorRegister.setTaskType(BorrowConstant.AUDIT_TYPE_BORROW);
        //开始时生成登记号 并且插入
        String finalRegist = borRegisterService.producePolicyNum(cmsBorRegister);
        cmsBorRegister.setRegisterNum(finalRegist);
        long cmsBorRegisterId = borRegisterService.insertSelectId(cmsBorRegister);

        //登录id以及文件id插入到文件登记表中
        for(String borrowFileId : borrowIds){
            borRegisterService.insertBorrowRegFile(cmsBorRegisterId,borrowFileId,fileType);
        }

        //获取登记表的主键，记录其中
        String businessKey = String.valueOf(cmsBorRegisterId);

        ProcessInstance processInstance = null;
        Map<String, Object> variables = new HashMap<String, Object>();
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        //查找该登录人账户所登录的账户对应的用户id
        User nameUser = identityService.createUserQuery().userId(String.valueOf(user.getUserId())).singleResult();
        if(nameUser==null){
            identityService.setAuthenticatedUserId(user.getUsername());
        }else{
            identityService.setAuthenticatedUserId(String.valueOf(nameUser.getId()));
        }

        //如果流程具有 指定表达式，则替换改表达式
        if(StringUtils.isNotBlank(delegateUser)){
            variables.put(delegateUser,userName);
        }
        //如果流程具有 指定表达式，则替换改表达式
        if(StringUtils.isNotBlank(hallType)){
            variables.put("type",hallType);
        }
        processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
        String processInstanceId = processInstance.getId();
        //若启动的流程id存在，则启动成功
        if(processInstanceId!=null&&!"".equals(processInstanceId)){
            //若为线下借阅，则将借阅的档案设置为已借阅，不可他人借阅
            if (BorrowConstant.BORROW_TYPE_DOWN==Long.parseLong(borType)){
                /*判断文件类型及借出情况，根据文件类型储存文件id到借阅登记表中，并更新其余表的文件借阅状态*/
                //如果单件为null  则借阅的为单件,更新单件状态
                if(cmsSinItem!=null){
                    cmsSinItem.setItemStatus(2L);
                    cmsSinItemService.updateSinItemByPrimaryKeySelective(cmsSinItem);
                //如果件表为null 则当前借阅的为卷
                }else if(cmsJudItem==null){
                    cmsJudVolume.setVolStatus(2);
                    volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume);
                    Long voId = cmsJudVolume.getVolId();
                    volAndItemService.updateItemStatusByVoId(2L,voId);
                }else{
                    if(null!=cmsJudVolume){
                        //判断当前借阅的件的数量与卷包含的数量是否一致
                        Long voId = cmsJudVolume.getVolId();
                        List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(voId, 0);
                        //当借阅的件的数量与卷包含的数量一致时，同时需要修改卷的状态
                        if(cmsJudItems.size()==borrowIds.length){
                            cmsJudVolume.setVolStatus(2);
                            volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume);
                        }
                        volAndItemService.updateItemStatusByIds(2L,borrowIds);
                    }
                }
            }
            //若启动成功，则将其审核的流程记录在案
            CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
            //修改时间
            Date now = DateTimeUtil.getNow();
            cmsBorAuditing.setCreateTime(now);
            cmsBorAuditing.setBorRegisterId(cmsBorRegisterId);
            cmsBorAuditing.setAuditUserId((long)user.getUserId());
            cmsBorAuditing.setAuditType((long)BorrowConstant.AUDIT_TYPE_BORROW);
            cmsBorAuditing.setAuditUserView("发起借阅流程");
            cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);
            borAuditService.insert(cmsBorAuditing);
            return new CmsResult(1,"借阅成功",0);
        }else{
            return new CmsResult(0,"借阅申请失败，请稍后再试！",0);
        }
    }

    /**
     * @author:zyp
     * @description 发起续借流程
     * @date: 2019/3/21 15:14
     * @return 
     */
    @ApiOperation(value = "发起续借流程")
    @RequestMapping(value = "/sendRenewAct")
//    @RequiresPermissions("cms:borAudit:read")
    @ResponseBody
    public Object sendRenewAct(CmsBorRegister cmsBorRegister,String userName,String delegateUser) throws Exception {
        /*获取当前登录用户信息*/
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        //获取当前借阅的最新的流程
        UpmsActDefine upmsActDefine = actDefineService.getNewAct("renewBor");
        if(upmsActDefine==null){
            return new CmsResult(0,"借阅失败，请找系统管理员确认流程是否定义",0);
        }
        //获取流程的唯一标识
        String key = upmsActDefine.getAdKey();
        cmsBorRegister.setUpdateTime(new Date());
        cmsBorRegister.setTaskType(BorrowConstant.AUDIT_TYPE_RENEW);
        borRegisterService.updateByPrimaryKeySelective(cmsBorRegister);
        //获取登记表的主键，记录其中
        String businessKey = String.valueOf(cmsBorRegister.getId());
        ProcessInstance processInstance = null;
        Map<String, Object> variables = new HashMap<String, Object>();
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        User nameUser = identityService.createUserQuery().userFirstName(username).singleResult();
        if(nameUser==null){
            identityService.setAuthenticatedUserId(username);
        }else{
            identityService.setAuthenticatedUserId(nameUser.getId());
        }
        //如果流程具有 指定表达式，则替换改表达式
        if(StringUtils.isNotBlank(delegateUser)){
            variables.put(delegateUser,userName);
        }
        processInstance = runtimeService.startProcessInstanceByKey(key, businessKey, variables);
        String processInstanceId = processInstance.getId();
        if(processInstanceId!=null&&!"".equals(processInstanceId)){
            //若启动成功，则将其审核的流程记录在案
            CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
            //修改时间
            Date now = DateTimeUtil.getNow();
            cmsBorAuditing.setCreateTime(now);
            cmsBorAuditing.setBorRegisterId(cmsBorRegister.getId());
            cmsBorAuditing.setAuditUserId((long)user.getUserId());
            cmsBorAuditing.setAuditType(1L);
            cmsBorAuditing.setAuditUserView("发起续借流程");
            cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);
            borAuditService.insert(cmsBorAuditing);
            return new CmsResult(1,"续借成功",0);
        }else{
            return new CmsResult(0,"借阅申请失败，请稍后再试！",0);
        }
    }

}